package com.megvii.koala.tv.fragment;

import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;

import com.megvii.koala.base.KoalaFragment;
import com.megvii.koala.tv.activity.MainActivity;

/**
 * Created by linyue on 16/1/24.
 */
abstract public class BaseFragment<PARAM> extends KoalaFragment
{
    protected PARAM param;

    protected View focusedView;

    @Override
    public void onResume()
    {
        super.onResume();
        //TODO 判断这个view是不是自己的child
        if (focusedView != null)
        {
            focusedView.requestFocus();
        }
    }

    @Override
    public void onPause()
    {
        super.onPause();
        focusedView = getActivity().getCurrentFocus();
    }

    public PARAM getParam()
    {
        return param;
    }

    public void setParam(PARAM param)
    {
        this.param = param;
    }

    public void startFragment(Class<? extends KoalaFragment> clazz, Object param)
    {
        MainActivity activity = (MainActivity) getActivity();
        activity.startFragment(clazz, param);
    }

    public void finish()
    {
        MainActivity activity = (MainActivity) getActivity();
        activity.finishOneFragment();
    }

    public void finishFragments()
    {
        MainActivity activity = (MainActivity) getActivity();
        activity.finishFragments();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event)
    {
        if (keyCode == KeyEvent.KEYCODE_BACK)
        {
            BaseFragmentListener baseListener = getBaseFragmentListener();
            if (baseListener != null)
            {
                baseListener.onBackPressed();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    abstract public BaseFragmentListener getBaseFragmentListener();

    public interface BaseFragmentListener
    {
        public void onBackPressed();
    }
}
